//app.js

let config = require('./utils/config')
let logger = require('./utils/logger')
let httpFunc = require('./utils/http')
var logining = false
App({
  onLaunch: function (options) {
    this.globalData.userId = wx.getStorageSync('userId')
    this.globalData.token = wx.getStorageSync('token')
    this.globalData.cityCode = wx.getStorageSync('cityCode')
    this.globalData.cityName = wx.getStorageSync('cityName')
    this.globalData.cityTitle = wx.getStorageSync('cityTitle')
    
    logger.debug('小程序开始启动:', options)
    this.http = httpFunc(this, wx)
    logger.debug('初始化http client 完成', this.http)
    
    if (!this.globalData.cityCode) {
      this.setLocation('00303', '嘉兴市')
      this.http.post({
        path: '/user/update',
        data: {
          id: app.globalData.userId,
          countryCode: '0',
          provinceCode: '003',
          cityCode: '00303'
        }
      })
    }
  },
  onShow: function (options) {
    this.globalData.shareGuide = [1007, 1008, 1036].indexOf(options.scene) > -1
  },
  login (option) {
    if (logining) {
      setTimeout(function () {
        if (option && option.success) {
          option.success()
        }
      }, 500)
      return
    }
    logger.debug('开始登录...')
    let wx = wx
    if (option && option.wx) {
      wx = option.wx
    }
    
    let that = this
    logining = true
    wx.login({
      success (loginRes) {
        var code = loginRes.code
        logger.debug('微信登录成功:', loginRes)
        
        wx.getUserInfo({
          success (res) {
            logger.debug('获取用户信息成功:', res)
            
            that.globalData.userInfo = res.userInfo
            
            let data = {
              code: code,
              rawData: res.rawData,
              signature: res.signature,
              encryptedData: res.encryptedData,
              iv: res.iv
            }
            
            that.http.post({
              path: '/wx/login',
              data: data,
              success (response) {
                logger.debug('三方服务器登录成功', response)
                
                let data = response
                var token = data.token
                var userId = data.id
                wx.setStorageSync('token', token)
                wx.setStorageSync('userId', userId)
                
                that.globalData.token = token
                that.globalData.userId = userId
                
                if (option && option.success) {
                  option.success(response)
                }
              },
              complete () {
                logining = false
                if (option && option.complete) {
                  option.complete()
                }
              }
            })
            
          },
          fail () {
            wx.navigateTo({
              url: '/pages/mine/mine'
            })
          },
          complete () {
            logining = false
          }
        })
      },
      fail () {
        wx.openSetting({
          success: function (data) {
            if (data) {
              if (data.authSetting['scope.userInfo'] == true) {
                logger.info('设置权限成功')
              }
            }
          }
        })
      },
      complete () {
        logining = false
        if (option && option.complete) {
          option.complete()
        }
      }
    })
  },
  getLocation () {
    let that = this
    wx.showLoading({
      title: '定位中'
    })
    
    wx.getLocation({
      success (res) {
        wx.hideLoading()
        
        let data = {
          longitude: res.longitude,
          latitude: res.latitude
        }
        
        that.http.post({
          path: '/wx/login',
          data: data,
          success (response) {
            wx.setStorageSync('cityName', data.cityName)
            
            this.globalData.cityName = data.cityName
          }
        })
      },
      fail () {
        wx.setStorageSync('cityName', config.defaultCityName)
        
        this.globalData.cityName = config.defaultCityName
      }
    })
  },
  setLocation (cityCode, cityName) {
    this.globalData.cityCode = cityCode
    this.globalData.cityName = cityName
    this.globalData.cityTitle = cityName.replace('市', '')
    
    wx.setStorage({key: 'cityCode', data: cityCode})
    wx.setStorage({key: 'cityName', data: cityName})
    wx.setStorage({key: 'cityTitle', data: this.globalData.cityTitle})
  },
  globalData: {
    userInfo: null,
    status: '',
    token: '',
    userId: '',
    cityTitle: '',
    cityName: '',
    cityCode: '',
    reLaunch: false,
    shareGuide: false
  },
  http: undefined
})